package com.shuai.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.shuai.constant.LoginTypeConstant;
import com.shuai.context.BaseContext;
import com.shuai.dto.ProjectDTO;
import com.shuai.dto.ProjectPageQueryDTO;
import com.shuai.entity.File;
import com.shuai.entity.Project;
import com.shuai.entity.ProjectUserRelation;
import com.shuai.mapper.FileMapper;
import com.shuai.mapper.ProjectMapper;
import com.shuai.mapper.ProjectUserRelationMapper;
import com.shuai.mapper.UserMapper;
import com.shuai.result.PageResult;
import com.shuai.service.ProjectService;
import com.shuai.vo.ProjectUserRelationVO;
import com.shuai.vo.ProjectVO;
import com.shuai.vo.VisualProjectVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

import java.util.List;

@Service
@Slf4j
public class ProjectServiceImpl implements ProjectService{
    
    @Autowired
    private ProjectMapper projectMapper;

    @Autowired
    FileMapper fileMapper;

    @Autowired
    ProjectUserRelationMapper projectUserRelationMapper;

    @Autowired
    private BaseContentService baseContentService;

    @Autowired
    private UserMapper userMapper;
    /**
     * 新增项目
     * @param projectDTO
     */
    @Override
    @Transactional
    public void saveWithFileAndTeam(ProjectDTO projectDTO) {
        Project project = new Project();
        //对象属性拷贝
        BeanUtils.copyProperties(projectDTO,project);
        //设置项目所属企业id
        project.setEnterpriseId(baseContentService.getEnterpriseId());
        projectMapper.insert(project);

        //插入文件列表
        List<File> files = projectDTO.getFiles();
        Long projectId = project.getId();
        //向文件表插入n条数据
        if(files != null && files.size() > 0){
            files.forEach(file -> {
                file.setProjectId(projectId);
            });
            //向口味表插入n条数据
            fileMapper.insertBatch(files);
        }

        //插入团队列表
        List<ProjectUserRelation> relations = projectDTO.getRelations();
        //向口味表插入n条数据
        if(relations != null && relations.size() > 0){
            files.forEach(relation -> {
                relation.setProjectId(projectId);
            });
            //向口味表插入n条数据
            projectUserRelationMapper.insertBatch(relations);
        }
    }

    /**
     * 分页查询项目信息
     * @param projectPageQueryDTO
     *@return PageResult
     * */
    @Override
    public PageResult pageQuery(ProjectPageQueryDTO projectPageQueryDTO) {

        //分页查询
        PageHelper.startPage(projectPageQueryDTO.getPage(),projectPageQueryDTO.getPageSize());

        //设置企业id
        projectPageQueryDTO.setEnterpriseId(baseContentService.getEnterpriseId());
        Page<Project> page = projectMapper.pageQuery(projectPageQueryDTO);

        Long total = page.getTotal();
        List<Project> records = page.getResult();

        //封装分页结果
        return new PageResult(total, records);
    }

    /**
     *根据id查询项目信息
     * */
    @Override
    public ProjectVO getById(Long id) {
        Project project = projectMapper.getById(id);
        ProjectVO projectVO = new ProjectVO();
        //对象属性拷贝
        BeanUtils.copyProperties(project,projectVO);

        //查询项目关联的文件列表
        List<File> files = fileMapper.getByProjectId(id);
        projectVO.setFiles(files);

        //查询项目关联的团队列表
        List<ProjectUserRelationVO> relations = projectUserRelationMapper.getByProjectId(id);
        projectVO.setRelations(relations);
        return  projectVO;
    }

    //TODO 删除项目
    @Override
    @Transactional
    public void deleteWithFileAndTeamById(Long id) {

        //删除项目
        projectMapper.deleteByProjectId(id);

        //删除项目文件和团队关系
        fileMapper.deleteByProjectId(id);
        projectUserRelationMapper.deleteByProjectId(id);

    }

    @Override
    public PageResult<VisualProjectVO> visualPageQuery(ProjectPageQueryDTO projectPageQueryDTO) {
        //分页查询
        PageHelper.startPage(projectPageQueryDTO.getPage(),projectPageQueryDTO.getPageSize());

        Long userId = BaseContext.getCurrentLoginInfo().getId();
        Page<VisualProjectVO> page = projectMapper.visualProjectPageQuery(projectPageQueryDTO,userId);
        Long total = page.getTotal();

        List<VisualProjectVO> records = page.getResult();

        //封装分页结果
        return new PageResult(total, records);
    }

    /**
     * 修改项目信息
     * @param projectDTO
     * */
    @Override
    @Transactional
    public void update(ProjectDTO projectDTO) {
        //将DTO转换为实体对象,属性拷贝
        Project project = new Project();
        BeanUtils.copyProperties(projectDTO,project);
        projectMapper.update(project);
        Long projectId = project.getId();

        //更新文件列表
        List<File> files = projectDTO.getFiles();
        fileMapper.deleteByProjectId(projectId);
        //向文件表插入n条数据
        if(files != null && files.size() > 0){
            files.forEach(file -> {
                file.setProjectId(projectId);
            });
            //向口味表插入n条数据
            fileMapper.insertBatch(files);
        }

        //更新团队列表
        List<ProjectUserRelation> relations = projectDTO.getRelations();
        projectUserRelationMapper.deleteByProjectId(projectId);
        //向口味表插入n条数据
        if(relations != null && relations.size() > 0){
            relations.forEach(relation -> {
                relation.setCreateTime(LocalDateTime.now());
                relation.setProjectId(projectId);
                String username = relation.getUsername();
                Long userId = userMapper.getUserIdByUsername(username);
                relation.setUserId(userId);
            });
            //向口味表插入n条数据
            projectUserRelationMapper.insertBatch(relations);
        }
    }

    /**
     * 根据ids批量删除项目（删除项目相关的文件和团队关系）
     * @param ids
     */
    @Override
    @Transactional
    public void deleteWithFileAndTeam(List<Long> ids) {

        //TODO 权限问题（是否允许删除）

        //删除项目
        projectMapper.deleteBatch(ids);

        //删除项目文件和团队关系
        for (Long id : ids) {
            fileMapper.deleteByProjectId(id);
            projectUserRelationMapper.deleteByProjectId(id);
        }
    }
}
